﻿using River.Core;
using System;
using System.Collections.Generic;
using System.IO;

namespace River.IntAI.ISdk
{
    /// <summary>
    /// 图片识别文字
    /// </summary>
    public class OcrUtils
    {
        /// <summary>
        /// 调用百度 API 识别文字
        /// </summary>
        /// <param name="imgPath">图片路径</param>
        /// <param name="accurate">是否高精度</param>
        /// <returns></returns>
        public BaiduRetOcr Recognize(string imgPath, bool accurate)
        {
            try
            {
                string appId, apiKey, secretKey;
                if(!RiverAuth.Instant.GetOcrApiConfig(out appId, out apiKey, out secretKey))// 读取应用配置
                    return new BaiduRetOcr();
                var client = new Baidu.Aip.Ocr.Ocr(apiKey, secretKey);
                client.Timeout = (int)ConfigUtil.GetConfig(EnumConfigKey.ClientTimeOut, 60 * 1000);
                var image = File.ReadAllBytes(imgPath);
                // 调用通用文字识别, 图片参数为本地图片，可能会抛出网络等异常，请使用try/catch捕获
                var result = client.GeneralBasic(image);
                // 如果有可选参数
                var options = new Dictionary<string, object>{
                    {"language_type", "CHN_ENG"},
                    {"detect_direction", "true"},
                    {"detect_language", "true"},
                    {"probability", "true"}
                };
                // 带参数调用通用文字识别, 图片参数为本地图片
                if (accurate)
                {
                    result = client.AccurateBasic(image, options);
                }
                else
                    result = client.GeneralBasic(image, options);
                return result.ToObject<BaiduRetOcr>();
            }
            catch (Exception ex) {
                MsgUtil.Error("识别错误:"+ex.Message);
                return new BaiduRetOcr();
            }
            finally
            {
            }
        }
    }
    

    /// <summary>
    /// 百度API 识别文字返回的对象
    /// </summary>
    public class BaiduRetOcr
    {
        public RetWordsItem[] words_result { get; set; }
        public string log_id { get; set; }
        public int words_result_num { get; set; }
        public int language { get; set; }
        public int direction { get; set; }
        public int error_code { get; set; }
        public string error_msg { get; set; }
    }
    /// <summary>
    /// 识别的每一条词句对象
    /// </summary>
    public class RetWordsItem
    {
        public probabilityItem probability { get; set; }//识别概率
        public string words { get; set; }// 识别的文字
    }
    /// <summary>
    /// 识别概率
    /// </summary>
    public class probabilityItem
    {
        public decimal average { get; set; }// 平均值
        public decimal min { get; set; }// 最小值
        public decimal variance { get; set; }// 方差
    }
}
